<?php
namespace app\user\controller;

use tp5_lib\common\controller\BaseController;
use app\user\service\UserService;
use tp5_lib\user\logic\UserModule;
use think\facade\Session;

/**
 * 用户中心
 * 修改信息、修改密码等操作
 */
class IndexController extends BaseController
{
    public $user;
    // 初始化
    protected function initialize()
    {
        $this->user=$this->checkLogin();
    }
    public function index()
    {
        $this->assign("user",$this->user);
        if($this->request->isMobile()){
            $this->redirect("mobile/index");
        }
        $module=new UserModule();
        if(!$config=$module->read("user")){
            $menu=[];
        }
        $menu=$config["menu"];
        $this->assign("menu",$menu);
        return $this->fetch("index/mobile/index");
    }
    //退出登录
    public function logout()
    {
        Session::clear("user");
        $this->success("退出成功",url("user/login/login"));
    }
    public function updatePassword()
    {
        if(empty($this->user["password"])){
            $this->redirect("login/getback");
        }
        $this->assign("user",$this->user);
        $path = $this->request->isMobile() ? "index/mobile/" : "index/pc/" ;
        return $this->fetch($path."updatePassword");
    }
    public function _empty($name)
    {
        $methods=get_class_methods(UserService::class);
        if(!preg_match("/^do/",$name)){
            foreach($methods as $method){
                if($name === strtolower($method)){
                    $this->assign("user",$this->user);
                    $path = $this->request->isMobile() ? "index/mobile/" : "index/pc/" ;
                    return $this->fetch($path.$method);
                }
            }
        }
        else{
            $name=substr($name,2);
            foreach($methods as $method){
                if($name === strtolower($method)){
                    $service=new UserService();
                    $result=call_user_func([$service,$method],$this->user,$_REQUEST);
                    if(!$result){
                        $this->error($service->getError());
                    }
                    $this->success("修改成功",url("index"));
                }
            }
        }
        $this->error("未定义的操作");
    }
}
